﻿using DLL.Models;
using DLL.Models.CheckpointModels;
using DLL.Repository;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Deptus.TestEncounter.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CheckpointController : ControllerBase
    {
        private IEmployeeRepository EmployeeRepository;
        private IShiftRepositiry ShiftRepositiry;

        public CheckpointController(IEmployeeRepository employeeRepository, IShiftRepositiry shiftRepositiry)
        {
            EmployeeRepository = employeeRepository;
            ShiftRepositiry = shiftRepositiry;
        }


        [HttpPost("StartShift")]
        public async Task<IActionResult> StartShift([FromBody] StartShift workStartShift)
        {
            WorkShift workShift = new WorkShift();
            try
            {
              var NotClosedShifts = await  ShiftRepositiry.GetNotClosedByEmployee(workStartShift.EmployeeId);

                if (NotClosedShifts.ToList().Count !=0)
                    throw new Exception("Есть незакрытая смена");

                if( await EmployeeRepository.GetById(workStartShift.EmployeeId) ==null )
                    throw new Exception("Человек дверью ошибся");

                workShift.Id = Guid.NewGuid();
                workShift.EmployeeId = workStartShift.EmployeeId;
                workShift.StartOfShift = workStartShift.StartOfShift;
                workShift.EndOfShift = workStartShift.StartOfShift;
                workShift.WorkedOut = 0;
                workShift.Done = false;
                await ShiftRepositiry.Create(workShift);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
            return Ok(workShift);
        }


        [HttpPost("EndShift")]
        public async Task<IActionResult> EndShift( [FromBody] EndShift workEndShift)
        {
            WorkShift shift= new WorkShift();
            try
            {
                var NotClosedShifts = await ShiftRepositiry.GetNotClosedByEmployee(workEndShift.EmployeeId);

                if (NotClosedShifts == null || (NotClosedShifts.ToList().Count == 0 ))
                {
                    throw new Exception("Нет начатой смены");
                }

                shift = NotClosedShifts.First();

                shift.EndOfShift = workEndShift.EndOfShift;
                var WorkedOut = workEndShift.EndOfShift - shift.StartOfShift;

                shift.WorkedOut = (Int32)WorkedOut.Value.TotalHours;

                shift.Done = true;


                var tmp = ShiftRepositiry.Update(shift);

            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
            return Ok(shift);
        }


    }
}
